/*
 ============================================================================
 Name		: CBufferManager.cpp
 Author	  : lin.chaoming
 Version	 : 1.0
 Copyright   : do1
 Description : CCBufferManager implementation
 ============================================================================
 */
#include <EZstream.h>
#include "BufferManager.h"

CEZZStream::CEZZStream()
:iOutputPointer(NULL), iOutputBufferLength(0)
{

}
     
CBufferManager* CBufferManager::NewL(const TDesC8& aInput, CBufFlat& aOutput, TInt aBufferSize)
{
     CBufferManager* self = CBufferManager::NewLC(aInput, aOutput, aBufferSize);
     CleanupStack::Pop();
     return self;
}

CBufferManager* CBufferManager::NewLC(const TDesC8& aInput, CBufFlat& aOutput, TInt aBufferSize)
{
     CBufferManager* self = new (ELeave) CBufferManager(aOutput);
     CleanupStack::PushL(self);
     self->ConstructL(aInput, aBufferSize);
     return self;
}

void CBufferManager::ConstructL(const TDesC8& aInput, TInt aBufferSize)
{
     if(aBufferSize <= 0)
     {
          User::Leave(KErrArgument);
     }

     iBufferSize = aBufferSize;

     iInputBuffer = new (ELeave) TUint8[iBufferSize];
     iOutputBuffer = new (ELeave) TUint8[iBufferSize];

     iInputDescriptor.Set(iInputBuffer, 0, iBufferSize);
     iOutputDescriptor.Set(iOutputBuffer, 0, iBufferSize);
     
     iInput = HBufC8::NewL(aInput.Length());
     *iInput = aInput;
}

CBufferManager::~CBufferManager()
{
     delete [] iInputBuffer;
     delete [] iOutputBuffer;
     
     delete iInput;
}

CBufferManager::CBufferManager(CBufFlat& aOutput)
:iOutput(aOutput), iInput(NULL), iInputDescriptor(NULL,0), iOutputDescriptor(NULL,0)
{
}


void CBufferManager::InitializeL(CEZZStream& aZStream)
{
     NeedInputL(aZStream);
     aZStream.SetOutput(iOutputDescriptor);
}

void CBufferManager::NeedInputL(CEZZStream& aZStream)
{
     TInt length = (iBufferSize > iInput->Length()) ? iInput->Length() : iBufferSize;
     iInputDescriptor.Copy((TUint8*)iInput->Des().Ptr(), length);
     iInput->Des().Delete(0, length);

     aZStream.SetInput(iInputDescriptor);
}

void CBufferManager::NeedOutputL(CEZZStream& aZStream)
{
     TPtrC8 od = aZStream.OutputDescriptor();
     iOutput.InsertL(iOutput.Size(), od);
     aZStream.SetOutput(iOutputDescriptor);
}

void CBufferManager::FinalizeL(CEZZStream& aZStream)
{
     TPtrC8 od = aZStream.OutputDescriptor();
     iOutput.InsertL(iOutput.Size(), od);
}
